import React, { Component } from 'react';
import { Animated, TextInput, View, Image, StatusBar, Text, TouchableOpacity, FlatList, RefreshControl, DeviceEventEmitter, Platform } from 'react-native';
import TabBarTitle from '../components/TabBarTitle';
import { TabBarAnimationImage } from '../components/TabBarImage';
import Colors from '../constants/Colors';
import { width, unitWidth, statusBarHeight, titleHeight, height } from '../constants/AdapterUtil';
import Swiper from 'react-native-swiper';
import StickyListView from '../components/StickyListView';
import MoreClassification from '../components/MoreClassification';
import { DeleteTextView } from '../components/MyTextView';
import { HomeTypeModal } from '../components/Modal';
import { init, Geolocation, setLocatingWithReGeocode, setNeedAddress, addLocationListener, start, stop } from "react-native-amap-geolocation";
import Permissions from 'react-native-permissions';
import CommonUtil from '../constants/CommonUtil';
import { api_order_workorder_oneCate, api_index, api_goods_get_list, api_order_workorder_unread } from '../constants/HttpServices';
import { postFetch } from '../constants/HttpExtension';
import { contactBrowser } from '../constants/Gobrowser';
import { AddShoppingCartButton, AddShoppingCartButton2 } from '../components/Button';
import AreaPicker from '../components/AreaPicker';
import FastImage from 'react-native-fast-image';

export default class HomeScreen extends Component {
    static navigationOptions = ({ navigation, jumpToIndex, scene }) => ({
        title: 'home',
        tabBarLabel: ({ focused }) => (
            <TabBarTitle
                focused={focused}
                title={'首页'}
            />
        ),
        tabBarIcon: ({ focused }) => (
            <TabBarAnimationImage
                focused={focused}
                hasSelect={require('../res/ic_home_c.png')}
                noSelect={require('../res/ic_home_n.png')}
            />
        ),
        tabBarOnPress: (options) => {
            DeviceEventEmitter.emit('tabClick', '');
            options.defaultHandler();
        },
        tabBarOnLongPress: (options) => {
            return
        },
    });

    constructor(props) {
        super(props)
        this.state = {
            CarouselList: [],
            brandList: [],
            list: [],
            showSxMore: false,
            district: '',
            unreadCount: 0,

            oneCate: [],//一个分类
            chooseCate: {},
            desc: '1',//1综合降序,2综合升序,3销量降序,4销量升序，5价格降序，6价格升序
        }
    }

    componentDidMount() {
        // 使用自己申请的高德 App Key 进行初始化
        init({
            ios: "f9ddb23d4a560c522d26c82185d15096",
            android: "807ebf9db8e92b1a5deca118b50922be"
        });
        Platform.OS == 'android' ?
            // android
            setNeedAddress(true)
            :
            // ios
            setLocatingWithReGeocode(true);
        addLocationListener(this.getAddress.bind(this));
        start();

        this.checkVersion();
        if (this.refs.StickyListView) {
            this.refs.StickyListView._onRefresh();
        }
        this.props.navigation.addListener('didFocus', payload => {
            this.requestLocationPermission()
            this.getIndex();
            this.messageNoRead();
            CommonUtil.getSetting();
            CommonUtil.getUserInfo();
        })
    }

    componentWillUnmount() {
        if (AreaPicker.myPicker) {
            AreaPicker.myPicker.hide();
        }
    }

    requestLocationPermission() {
        try {
            Permissions.request('location', {
                type: 'always',
            }).then(response => {
                console.log(response)
                if (response === 'authorized') {

                }
            }).catch(err => {
                console.log(err)
            })
        } catch (err) {
            console.log(err);
        }
    }

    getAddress(result) {
        global.locationInfo = {
            province: result.province,
            city: result.city,
            area: result.district,
            lat: result.latitude,
            lng: result.longitude
        }
        this.setState({
            district: result.district,
        })
        if (this.refs.StickyListView) {
            this.refs.StickyListView._onRefresh();
        }
        stop();
    }

    render() {
        return (
            <View style={{ flex: 1, backgroundColor: Colors.colorF5 }}>
                <StatusBar
                    animated={false} //指定状态栏的变化是否应以动画形式呈现。目前支持这几种样式：backgroundColor, barStyle和hidden
                    hidden={false}  //是否隐藏状态栏。
                    translucent={true}//指定状态栏是否透明。设置为true时，应用会在状态栏之下绘制（即所谓“沉浸式”——被状态栏遮住一部分）。常和带有半透明背景色的状态栏搭配使用。
                    barStyle={'dark-content'} // enum('default', 'light-content', 'dark-content')
                    backgroundColor={'rgba(0,0,0,0)'}
                />
                <View style={{ height: statusBarHeight + titleHeight, width: width, backgroundColor: Colors.white }}>
                    <View style={{ marginTop: statusBarHeight, height: titleHeight, width: width, backgroundColor: Colors.white, flexDirection: 'row', borderWidth: 0.5, borderBottomColor: Colors.colorE8, borderColor: Colors.transparent }}>
                        <TouchableOpacity style={{ flex: 1.2, marginLeft: 16 * unitWidth, flexDirection: 'row', alignItems: 'center' }} activeOpacity={0.7}
                            onPress={() => {
                                AreaPicker.pickerInitcallback({
                                    success: (province, city, area) => {
                                        global.locationInfo.province = province;
                                        global.locationInfo.city = city;
                                        global.locationInfo.area = area;
                                        this.setState({
                                            district: area,
                                        })
                                        this.refs.StickyListView._onRefresh();
                                    }
                                }, true);
                            }}>
                            <Text style={{ fontSize: 13, color: Colors.black }}>{this.state.district}</Text>
                            <Image source={require('../res/ic_arrow_1.png')}
                                style={{ width: 13 * unitWidth, height: 9 * unitWidth, marginLeft: 3 * unitWidth }}
                                resizeMode='stretch' />
                        </TouchableOpacity>
                        <View style={{ flex: 5, alignItems: 'center', justifyContent: 'center' }}>
                            <TouchableOpacity style={{ width: 250 * unitWidth, height: 29 * unitWidth, borderRadius: 20, backgroundColor: Colors.colorEF, flexDirection: 'row', alignItems: 'center', }}
                                onPress={() => {
                                    this.props.navigation.navigate('Search')
                                }}>
                                <Image source={require('../res/ic_search.png')}
                                    style={{ width: 13 * unitWidth, height: 14 * unitWidth, marginHorizontal: 10 * unitWidth }}
                                    resizeMode='stretch' />
                                <Text style={{ fontSize: 10 * unitWidth }}>搜索</Text>
                            </TouchableOpacity>
                        </View>
                        <TouchableOpacity style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}
                            onPress={() => { this.props.navigation.navigate('Message') }}>
                            <Image source={require('../res/ic_message.png')}
                                style={{ width: 20 * unitWidth, height: 18 * unitWidth }}
                                resizeMode='stretch' />
                            {this.state.unreadCount > 0 ?
                                <View style={{
                                    width: 8 * unitWidth, alignItems: 'center', justifyContent: 'center',
                                    height: 8 * unitWidth,
                                    backgroundColor: Colors.colorRed,
                                    borderRadius: 4 * unitWidth, position: 'absolute', right: 12 * unitWidth, top: 12 * unitWidth
                                }}>
                                    {/* <Text style={{ fontSize: 10 * unitWidth, color: Colors.white }}>{this.state.unreadCount}</Text> */}
                                </View> : null}
                        </TouchableOpacity>
                    </View>
                </View>
                <View style={{ flex: 1 }}>
                    <StickyListView
                        ref='StickyListView'
                        list={this.state.list}
                        showTopBtn={true}
                        numOfLine={2}
                        scrollEnabled={!this.state.showSxMore}
                        getList={this.getData.bind(this)}
                        headerView={
                            <View style={{ alignItems: 'center' }}>
                                {
                                    this.state.CarouselList && this.state.CarouselList.length > 0 ?
                                        <View style={{ width: width, minHeight: 174 * unitWidth }}>
                                            <Swiper style={{ width: width, height: 174 * unitWidth }} loop={true} autoplay={true} dotStyle={{ marginBottom: -20 * unitWidth }} activeDotStyle={{ marginBottom: -20 * unitWidth }}>
                                                {this.getCarouselView()}
                                            </Swiper>
                                        </View> : null
                                }
                                <Image source={require('../res/ic_djdzz.png')}
                                    style={{ width: 101 * unitWidth, height: 13 * unitWidth, marginVertical: 10 * unitWidth }}
                                    resizeMode='stretch' />
                                <MoreClassification ref='MoreClassification'
                                    style={{ backgroundColor: Colors.white, height: 190 * unitWidth }}
                                    list={this.state.brandList}
                                    categoryItem={this.categoryItem}
                                    onItemClick={(item) => {
                                        this.props.navigation.navigate('ServiceProviderList', { classify: item.classify })
                                    }} />
                                <Image source={require('../res/ic_sc.png')}
                                    style={{ width: 60 * unitWidth, height: 14 * unitWidth, marginVertical: 10 * unitWidth }}
                                    resizeMode='stretch' />
                            </View>
                        }
                        stickView={
                            <View style={{ height: 68 * unitWidth, backgroundColor: Colors.white, width: width }}>
                                <View style={{ flexDirection: 'row', height: 31 * unitWidth, alignItems: 'center' }}>
                                    <TouchableOpacity style={{ flex: 1, alignItems: 'center', justifyContent: 'center', flexDirection: 'row' }} activeOpacity={0.5}
                                        onPress={() => {
                                            this.setState({
                                                desc: this.state.desc == '1' ? '2' : '1'
                                            }, () => {
                                                this.refs.StickyListView._onRefresh();
                                            })
                                        }}>
                                        <Text style={{ color: this.state.desc == '1' || this.state.desc == '2' ? Colors.colorOrange : Colors.black }}>综合</Text>
                                        <Image source={CommonUtil.getDescArrow(this.state.desc, '1', '2')}
                                            style={{ width: 7 * unitWidth, height: 5 * unitWidth, marginLeft: 3 * unitWidth }}
                                            resizeMode='stretch' />
                                    </TouchableOpacity>
                                    <TouchableOpacity style={{ flex: 1, alignItems: 'center', justifyContent: 'center', flexDirection: 'row' }} activeOpacity={0.5}
                                        onPress={() => {
                                            this.setState({
                                                desc: this.state.desc == '3' ? '4' : '3'
                                            }, () => {
                                                this.refs.StickyListView._onRefresh();
                                            })
                                        }}>
                                        <Text style={{ color: this.state.desc == '3' || this.state.desc == '4' ? Colors.colorOrange : Colors.black }}>销量</Text>
                                        <Image source={CommonUtil.getDescArrow(this.state.desc, '3', '4')}
                                            style={{ width: 7 * unitWidth, height: 5 * unitWidth, marginLeft: 3 * unitWidth }}
                                            resizeMode='stretch' />
                                    </TouchableOpacity>
                                    <TouchableOpacity style={{ flex: 1, alignItems: 'center', justifyContent: 'center', flexDirection: 'row' }} activeOpacity={0.5}
                                        onPress={() => {
                                            this.setState({
                                                desc: this.state.desc == '5' ? '6' : '5'
                                            }, () => {
                                                this.refs.StickyListView._onRefresh();
                                            })
                                        }}>
                                        <Text style={{ color: this.state.desc == '5' || this.state.desc == '6' ? Colors.colorOrange : Colors.black }}>价格</Text>
                                        <Image source={CommonUtil.getDescArrow(this.state.desc, '5', '6')}
                                            style={{ width: 7 * unitWidth, height: 5 * unitWidth, marginLeft: 3 * unitWidth }}
                                            resizeMode='stretch' />
                                    </TouchableOpacity>
                                    <TouchableOpacity style={{ flex: 1, alignItems: 'center', justifyContent: 'center', flexDirection: 'row' }} activeOpacity={0.5}
                                        onPress={() => {
                                            if (!this.refs.HomeTypeModal.isShow()) {
                                                this.setState({
                                                    showSxMore: true
                                                }, () => {
                                                    this.refs.StickyListView.scrollTo(426 * unitWidth);
                                                    this.refs.HomeTypeModal.showModal();
                                                })
                                            } else {
                                                this.setState({
                                                    showSxMore: false
                                                }, () => {
                                                    this.refs.HomeTypeModal.hideModal();
                                                })
                                            }
                                        }}>
                                        <Image source={!this.state.showSxMore ? require('../res/ic_sx.png') : require('../res/ic_sx_o.png')}
                                            style={{ width: 13 * unitWidth, height: 13 * unitWidth }}
                                            resizeMode='stretch' />
                                        <Text style={{ marginLeft: 3 * unitWidth }}>筛选</Text>
                                    </TouchableOpacity>
                                </View>
                                <View style={{ flexDirection: 'row', height: 37 * unitWidth, alignItems: 'center', flexWrap: 'wrap' }}>
                                    {this.getScreenView()}
                                </View>
                            </View>
                        }
                        minHeight={height}
                        top={431 * unitWidth}
                        stickHeight={68 * unitWidth}
                        scrollStick={431 * unitWidth}
                        childView={(item, index) => {
                            return (
                                <View style={{ justifyContent: 'center', alignItems: 'center', width: width / 2, height: 230 * unitWidth }}>
                                    <TouchableOpacity style={{
                                        width: 172 * unitWidth, height: 215 * unitWidth,
                                        alignItems: 'center', backgroundColor: Colors.white, borderRadius: 7, paddingHorizontal: 2 * unitWidth
                                    }} activeOpacity={0.5} onPress={() => { this.props.navigation.navigate('GoodsDetail', { id: item.id }) }}>
                                        <FastImage source={{ uri: item.thumb }}
                                            style={{ width: 168 * unitWidth, height: 120 * unitWidth }}
                                            resizeMode={FastImage.resizeMode.cover} />
                                        <Text style={{ fontWeight: 'bold', color: Colors.black, fontSize: 16, marginVertical: 4 * unitWidth, alignSelf: 'flex-start' }}>{item.title}</Text>
                                        <View style={{ paddingHorizontal: 7 * unitWidth, borderWidth: 0.5, borderColor: Colors.colorRed, borderRadius: 5, alignSelf: 'flex-start' }}>
                                            <Text style={{ color: Colors.colorRed, fontSize: 10, }}>线下价格:￥{item.offlineprice}</Text>
                                        </View>
                                        <View style={{ alignSelf: 'flex-start', marginTop: 5 * unitWidth, flexDirection: 'row', alignItems: 'center', width: 172 * unitWidth }}>
                                            <Text style={{ color: Colors.colorRed, fontSize: 17, }}>￥{item.marketprice}</Text>
                                            <DeleteTextView text={'￥' + item.productprice} style={{ marginLeft: 3 * unitWidth }} />
                                            <AddShoppingCartButton
                                                style={{ position: 'absolute', right: 10 * unitWidth, }}
                                                id={item.id} />
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            )
                        }}
                        coverListView={
                            this.state.showSxMore ?
                                <TouchableOpacity style={{
                                    position: 'absolute', top: 68 * unitWidth,
                                    height: '100%', width: '100%', backgroundColor: 'rgba(0,0,0,0.3)'
                                }} activeOpacity={1}
                                    onPress={() => {
                                        this.setState({
                                            showSxMore: false
                                        }, () => {
                                            this.refs.HomeTypeModal.hideModal();
                                        })
                                    }} /> : <View />
                        } />
                    <HomeTypeModal ref='HomeTypeModal' cate={this.state.oneCate} onChoose={(item, type) => {
                        if (type == '3') {
                            this.setState({
                                showSxMore: false
                            })
                        }
                        this.setState({
                            chooseCate: item
                        }, () => {
                            this.refs.StickyListView._onRefresh();
                        })
                    }} />
                </View>
            </View>
        )
    }

    getCarouselView() {
        let views = []
        for (let i = 0, len = this.state.CarouselList.length; i < len; i++) {
            let item = this.state.CarouselList[i];
            views.push(
                <View key={i} style={{
                    justifyContent: 'center',
                    alignItems: 'center',
                }} activeOpacity={0.8} onPress={() => {
                    contactBrowser(item.link)
                }}>
                    <Image
                        source={{ uri: item.thumb }}
                        style={{
                            width: width, height: 174 * unitWidth,
                        }}
                        resizeMode='cover' />
                </View>
            )
        }
        return views;
    }

    getScreenView() {
        let views = []
        for (let i = 0, len = this.state.oneCate.length; i < len && i < 4; i++) {
            let item = this.state.oneCate[i];
            views.push(
                <TouchableOpacity key={i} style={{
                    justifyContent: 'center',
                    alignItems: 'center',
                    backgroundColor: this.state.chooseCate.id == item.id ? Colors.colorOrange : Colors.coloree,
                    borderRadius: 20,
                    paddingHorizontal: 7 * unitWidth,
                    marginHorizontal: 7 * unitWidth
                }} activeOpacity={0.5} onPress={() => {
                    if (this.state.chooseCate.id == item.id) {
                        this.setState({
                            chooseCate: {}
                        }, () => {
                            this.refs.StickyListView._onRefresh();
                            DeviceEventEmitter.emit('HomeChooseChange', {});
                        })
                    } else {
                        this.setState({
                            chooseCate: item
                        }, () => {
                            this.refs.StickyListView._onRefresh();
                            DeviceEventEmitter.emit('HomeChooseChange', item);
                        })
                    }
                }}>
                    <Text style={{
                        color: this.state.chooseCate.id == item.id ? Colors.white : Colors.color99,
                    }}>{item.name}</Text>
                </TouchableOpacity>
            )
        }
        return views;
    }

    checkVersion() {

    }

    //首页-（轮播图+导航栏+分类栏)
    getIndex() {
        let params = {

        }
        postFetch(api_index, params, {
            success: (response) => {
                this.setState({
                    CarouselList: response.result.adv.list,
                    brandList: response.result.nav.list,
                    oneCate: response.result.classify.list
                })
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //是否有消息未读
    messageNoRead() {
        let params = {

        }
        postFetch(api_order_workorder_unread, params, {
            success: (response) => {
                this.setState({
                    unreadCount: response.result.total
                })
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //获取商品列表
    getData(page) {
        let params = {
            page: page,
        }
        if (this.state.chooseCate && this.state.chooseCate.id) {
            params['cate'] = this.state.chooseCate.id
        }

        if (global.locationInfo.province && global.locationInfo.province != '全国') {
            params['province'] = global.locationInfo.province
        }
        if (global.locationInfo.province && global.locationInfo.city != '全国') {
            params['city'] = global.locationInfo.city
        }
        if (global.locationInfo.province && global.locationInfo.area != '全国') {
            params['area'] = global.locationInfo.area
        }

        if (this.state.desc == '1') {
            params['by'] = 'desc'
        } else if (this.state.desc == '2') {
            params['by'] = 'asc'
        } else if (this.state.desc == '3') {
            params['order'] = 'salesreal'
            params['by'] = 'desc'
        } else if (this.state.desc == '4') {
            params['order'] = 'salesreal'
            params['by'] = 'asc'
        } else if (this.state.desc == '5') {
            params['order'] = 'marketprice'
            params['by'] = 'desc'
        } else if (this.state.desc == '6') {
            params['order'] = 'marketprice'
            params['by'] = 'asc'
        }
        postFetch(api_goods_get_list, params, {
            success: (response) => {
                if (page == 1) {
                    this.setState({
                        list: response.result.list,
                    }, () => {
                        this.refs.StickyListView.onHasMore();
                    })
                } else {
                    if (response.result.list && response.result.list.length > 0) {
                        this.setState({
                            list: this.state.list.concat(response.result.list),
                        }, () => {
                            this.refs.StickyListView.onHasMore();
                        })
                    } else {
                        this.refs.StickyListView.onNoMore();
                    }
                }
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }
}